import router from "@/router";
import store from "@/store"
import {insertRoutes, clearRoutes} from "@/utils/asyncRoutes";
// @ts-ignore
import NProgress from "nprogress"
import "nprogress/nprogress.css"
// 进度条属性配置
NProgress.configure({
    easing: "ease", // 动画方式
    speed: 1000, // 递增进度条的速度
    showSpinner: false, // 是否显示加载 icon
    trickleSpeed: 200, // 自动递增间隔
    minimum: 0.3 // 初始化时的最小百分比
})

let loading = true
router.beforeEach(async (to, from, next) => {
    NProgress.start() //进度条开始
    if (to.name == "login") {
        //清除路由
        clearRoutes(router, store)
        //清楚登录信息
        store.commit("CLEAR_TOKEN")
        next()
    } else {
        if (getToken()) {
            //判断刷新操作
            if (!from.name && loading) {
                insertRoutes(router, store)
                next({...to, replace: true})
                loading = false
            } else {
                next()
            }
        } else {
            next({path: "/login", replace: true})
        }

    }
})

router.afterEach(() => {
    NProgress.done() // 进度条结束
})

const getToken = () => {
    store.commit("GET_TOKEN")
    return store.getters.token
}
